// components/Goods/goods.js
const app = getApp(),
  {
    $resHost
  } = app.globalData,
  _ = require('../../pages/Common/underscore.js');
import { getCityCode, getCityName, getAreaList } from '../../pages/Common/area';
let i = 0;
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    goodsId: {
      type: String,
      value: ''
    },
    isShow: {
      type: Boolean,
      value: false,
      observer(value) {
        if (value) {
          this.fetchInfo();
          this.setData({
            serviceOrgId: '',
            serviceOrgInfo: {},
            region: ['', '', ''],
            selectLen: 0
          });
        }
      }
    },
    noteUserId: {
      type: String,
      value: ''
    },
    notAddToEmit: {
      type: Boolean,
      value: false
    }
  },
  detached() {
    i = 0;
  },
  /**
   * 组件的初始数据
   */
  data: {
    selectLen: 0,
    arrBuyStatusTwo: [],
    //启用的sku组合id(不存在的属性组合也要不可选)
    qShow: false,
    //商品属性加载完成后再显示数量输入框，为了解决部分机型输入框文字不在输入框内的问题。
    isOpenPhone: false,
    id: '',
    oldshareEmployeeId: '',
    oldshareUserId: '',
    shareEmployeeId: '',
    //分享者的
    shareUserId: '',
    //分享者的
    orgId: '',
    goodsId: '',
    type: '',
    isEmployee: false,
    serviceInfo: {},
    isShow: false,
    //规则显示

    goodsInfo: {},
    spec: [],
    group: [],
    skus: [],
    price: '',
    //价格
    stock: '0',
    //库存
    skuId: '',
    selectText: '',
    unSelectText: '',
    quantity: '1',
    specName: '',
    spreadActivityId: '0',
    showCart: false,
    batchConversion: '',
    totalMoney: '',
    authoriz: false,
    actObj: {},
    actList: [],
    isFinishView: false,
    routeShareEmployeeId: 0,
    isQrcode: false,
    independentEntityId: '',
    icon: `${$resHost}/img/miniprogram/material/service2.png`,
    storeImg: `${$resHost}/img/miniprogram/home/storesImg.png`,
    cartPng: `background-image: url(${$resHost}/img/miniprogram/newDetail/cart.png)`,
    oneIcon: `${$resHost}/img/miniprogram/pay/address.png`,
    twoIcon: `${$resHost}/img/miniprogram/wishAssist/siteImg.png`,
    emptyImg: `${$resHost}/img/miniprogram//empty/empty_data.png`,
    uid: 0,
    eid: 0,
    roomId: '',
    liveUid: '',
    //直播带过来的
    liveEid: '',
    qqLiveId: '',
    //自己直播带来的
    skuImage: '',
    goodsFlashSaleData: false,
    isSplice: '',
    parentOrderId: '0',
    tabStatus: '',
    minSku: {},
    skuLength: '',
    //选中的数量
    hasLength: false,
    //是否全选
    employeeExclusive: false,
    minPrice: 0,
    isMask: true,
    isBrokerage: true,
    brokerageData: {},
    goodsInfoSku: [],
    cityName: '',
    notLocation: false,
    //是否定位
    userCityId: '',
    provinceId: '',
    cityId: '',
    areaId: '',
    serviceOrgId: '',
    serviceOrgInfo: {},
    goodsBody: "",
    detailMedia: "",
    registratioList: [],
    lat: '',
    lng: '',
    orderBy: '1',
    region: ['', '', ''],
    showService: false
  },
  pageLifetimes: {
    show: function () {
      if (this.data.notLocation && this.data.isShow) this.getCityDate();
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    fetchInfo() {
      if (!this.data.goodsId) {
        return false;
      }
      this.getInfo().then(data => {
        if (data.errCode == 0) {
          data = data.data;
          var goodsPrices = _.map(data.sku, sku => {
              return Number(sku.price);
            }),
            maxPrice = _.max(goodsPrices),
            minPrice = _.min(goodsPrices);
          let minSku = [];
          data.sku.map(p => {
            if (p.price == minPrice) {
              minSku.push(p);
            }
          });
          minSku.sort(function (a, b) {
            return parseFloat(a.splicePrice) - parseFloat(b.splicePrice);
          });
          let videoDate = {
            cover: data.videoImageId != '0' ? data.videoImage.url : data.video.cover || '',
            url: data.video.url || '',
            materialId: data.video.materialId || ''
          };
          this.setData({
            goodsInfo: data || {},
            goodsBody: data.goodsBody.replace(/(\n\r?)/g, '<br>').replace(/\s/g, '&nbsp;'),
            limitUser: data.limitUser,
            batchConversion: data.batchConversion,
            goodsType: data.goodsType,
            type: data.type,
            authoriz: xhs.getStorageSync('authoriz'),
            independentEntityId: data.independentEntityId,
            minSku: minSku[0],
            skuLength: data.sku.length || '',
            employeeExclusive: data.employeeExclusive,
            minPrice: minPrice,
            detailMedia: videoDate,
            cityName: (data.limitCityList.map(e => {
              return e.cityName;
            }) || []).join()
          }, () => {
            //获取地理信息 
            if (data.type == '1' || data.limitCityList.length > 0) {
              this.getCityDate();
            }
          });
          this.getBrokerage();
          this.fetchAttrValue(data || {});
        }
        //客服咨询
        //检测是机构
        let serviceInfo = {},
          {
            shareEmployeeId
          } = app.getTrack();
        if (this.data.type == 1) {
          serviceInfo = {
            orgId: this.data.id,
            serviceId: ''
          };
        } else if (this.data.type == 2) {
          serviceInfo = {
            orgId: '',
            serviceId: this.data.id || ''
          };
        } else {
          serviceInfo = {
            orgId: data.orgId,
            serviceId: shareEmployeeId || ''
          };
        }
        this.setData({
          serviceInfo
        });
      });
    },
    getInfo() {
      let {
        goodsId
      } = this.data;
      return app.$getData('/user/ec-goods/get-info', {
        goodsId
      }).then(data => {
        return data;
      });
    },
    showServiceFn() {
      let {
        group
      } = this.data;
      let a = group.filter(g => !g.valId);
      if (a.length !== 0) {
        return xhs.showToast({
          icon: 'none',
          title: '请选择' + a[0].name
        });
      }
      this.setData({
        showService: !this.data.showService
      });
    },
    closeMask() {
      this.setData({
        showService: !this.data.showService
      });
    },
    confirmService() {
      if (this.data.type == '1' && this.data.serviceOrgId == '' && this.data.registratioList.length != '0') {
        // 是品项&&没选机构&&所在城市商家不等于0
        return xhs.showToast({
          icon: 'none',
          title: '请选择服务商家'
        });
      }
      this.setData({
        isService: false,
        showService: false
      });
    },
    getCityDate() {
      let {
        goodsInfo,
        cityName
      } = this.data;
      getCityName().then(address => {
        this.setData({
          address
        }, () => {
          getCityCode().then(arr => {
            //arr实际是省市区id,不是code....      
            this.setData({
              provinceCode: arr ? arr[0] : '',
              cityCode: arr ? arr[1] : '',
              areaCode: arr ? arr[2] : '',
              notLocation: false
            }, () => {
              if (goodsInfo.type == '1') this.getOrganizationList(this.data.address);
              if (goodsInfo.limitCityList.length > 0) {
                var areas = goodsInfo.limitCityList.find(item => item.provinceId === arr[0] && item.cityId === arr[1]);
                if (areas) {
                  this.setData({
                    userCityId: areas.cityId
                  });
                } else {
                  xhs.showToast({
                    title: '仅限' + cityName + '用户购买',
                    icon: 'none',
                    mask: true
                  });
                }
              }
            });
          });
        });
      }, reason => {
        if (reason === '获取用户位置失败') {
          if (goodsInfo.limitCityList.length > 0) {
            this.setData({
              notLocation: true
            });
          }
          console.log("获取用户位置失败");
        }
      });
    },
    /**
     * 获取商品属性
     */
    fetchAttrValue(goodsInfo) {
      let param = {
        classId: goodsInfo.classId,
        goodsId: goodsInfo.id
      };
      app.$getData('/user/goods-attr/ec-get-attr-list', param).then(data => {
        if (data.errCode == 0) {
          let attrVals = data.data || [];
          let propAlias = goodsInfo.propAlias,
            specPic = goodsInfo.specPic,
            spec = [],
            //商品规格
            skuAttrId = [],
            //所选商品规格属性id
            //所选商品规格属性值 id
            skuAttrVal = _.chain(goodsInfo.sku).map(sku => {
              return sku.val;
            }).flatten(true).map(val => {
              skuAttrId.push(val.attrId);
              return val;
            }).value(),
            skuAttrValId; //所选商品规格属性规格名称
          skuAttrId = _.uniq(skuAttrId);
          skuAttrValId = _.uniq(skuAttrVal.map(val => {
            return val.attrValId;
          }));
          skuAttrVal = skuAttrValId.map(valId => {
            return _.findWhere(skuAttrVal, {
              attrValId: valId
            });
          });
          spec = _.filter(attrVals, attr => {
            let index = ~skuAttrId.indexOf(attr.id),
              alias;
            if (index) {
              alias = propAlias.filter(al => {
                return al.attrId === attr.id;
              })[0] || {
                aliasName: attr.attrName
              };
              //处理属性值
              attr.attrName = alias.aliasName;
              attr.attrVal = skuAttrVal.filter(val => {
                let is = attr.id === val.attrId;
                val.pic = '';
                if (is) {
                  //处理属性值对应的图片
                  val.pic = (specPic.filter(pic => {
                    return pic.attrValId === val.attrValId;
                  })[0] || {
                    url: ''
                  }).url;
                }
                return is;
              });
            }
            return index;
          });
          this.setData({
            spec: spec
          });
          this.createSku();
        } else {
          this.setData({
            price: goodsInfo.sku[0].price,
            stock: goodsInfo.sku[0].stock,
            skuId: goodsInfo.sku[0].id
          });
        }
      });
    },
    createSku(isSplice) {
      let {
        goodsInfo,
        spec,
        selectLen,
        targetLen
      } = this.data;
      //生成sku 属性
      //生成分组
      let arrBuyStatusTwo = [],
        skus = [],
        //sku 信息
        //属性图片
        specPic = goodsInfo.specPic || [],
        //属性值
        skuVal = _.flatten((goodsInfo.sku || []).map(sku => {
          targetLen = sku.val.length;
          if (sku.buyStatus == '1') {
            arrBuyStatusTwo.push(sku.val.map(val => {
              return val.attrValId;
            }));
          }
          skus.push({
            id: sku.id,
            price: isSplice == '1' ? sku.splicePrice : sku.price,
            goodsFlashSale: sku.goodsFlashSale,
            stock: parseInt(sku.stock || 0),
            val: sku.val.map(val => {
              return val.attrValId;
            })
          });
          return sku.val.map(val => {
            const currentData = specPic.find(pic => pic.attrValId === val.attrValId) || {
              url: '',
              isOrigin: false
            };
            return {
              id: val.id,
              attrId: val.attrId,
              valId: val.attrValId,
              name: val.attrValName,
              img: currentData.url,
              goodsSkuId: val.goodsSkuId,
              isOrigin: currentData.isOrigin,
              isDisabled: ''
            };
          });
        })),
        //属性分组
        group = _.chain(spec).filter(sp => {
          //过滤出销售属性
          return sp.isSell;
        }).sortBy(sp => {
          //将有图片的属性放在最前面
          if (sp.isAddImg) {
            return 0;
          } else {
            return 1;
          }
        }).map(sp => {
          //重新生成属性
          return {
            id: sp.id,
            name: sp.attrName,
            valId: '',
            val: _.chain(skuVal).filter(val => {
              return val.attrId === sp.id;
            }).uniq(val => {
              return val.valId;
            }).value()
          };
        }).filter(sp => {
          //过滤出没有属性值的销售属性
          return sp.val.length;
        }).value();

      // 默认
      for (var i = 0; i < group.length; i++) {
        if (group[i].val.length == '1') {
          group[i].valId = group[i].val[0].valId;
          selectLen = parseInt(selectLen) + 1;
        }
      }
      //分组注入属性值
      this.setData({
        selectLen,
        targetLen,
        arrBuyStatusTwo,
        group: group,
        skus: skus,
        stock: skus.length == 1 ? skus[0].stock : skus.reduce((prev, curr) => prev + +curr.stock, 0),
        skuId: skus.length == 1 ? skus[0].id : '',
        qShow: true
      });
      this.fetchPrice();
      // 默认选中
      this.fetchSelectText();
      this.fetchSelectSpecText();
    },
    getBrokerage() {
      // console.log(this.data.goodsInfo)
      let {
        goodsInfo
      } = this.data;
      let parmes = {
        type: 121,
        keyIds: goodsInfo.sku.map(item => {
          return item.id;
        })
      };
      app.$getData('/user/dealer-talent/brokerage', parmes).then(data => {
        if (data.errCode == 0) {
          // 1分润  3分销
          if (!(JSON.stringify(data.data) === '[]')) {
            if (data.data.shareType == 3) {
              goodsInfo.sku.forEach((item, index) => {
                item.getGoods = goodsInfo.enableSplicingPattern != '1' ? item.price : item.splicePrice;
                item.brokerageMoney = 0;
                data.data.prices.forEach((item1, index1) => {
                  if (item.id == item1.keyId) {
                    item.getGoods = item1.price;
                    item.brokerageMoney = ((goodsInfo.enableSplicingPattern != '1' ? item.price : item.splicePrice) - item1.price).toFixed(2);
                  }
                });
                item.brokerageName = item.val.map(item => {
                  return item.attrValName;
                }).toString();
              });
              // console.log(goodsInfo.sku)
            } else if (data.data.shareType == 1) {
              goodsInfo.sku.forEach((item, index) => {
                item.getGoods = `${parseFloat(data.data.rate)}%`;
                item.brokerageMoney = ((goodsInfo.enableSplicingPattern != '1' ? item.price : item.splicePrice) * parseFloat(data.data.rate) / 100).toFixed(2);
                item.brokerageName = item.val.map(item => {
                  return item.attrValName;
                }).toString();
              });
            }
          }
          this.setData({
            isBrokerage: JSON.stringify(data.data) === '[]',
            brokerageData: data.data,
            goodsInfoSku: goodsInfo.sku
          });
        }
      });
    },
    toggleVal(event) {
      let {
        liid,
        gid,
        idx,
        idxx,
        dib
      } = event.target.dataset;
      let {
        group,
        targetLen,
        selectLen,
        arrBuyStatusTwo
      } = this.data;
      var isCancel = false;
      //判断buyStatus  1启用  2不启用
      if (dib == 'disabled') {
        return;
      }
      if (liid === gid) {
        group[idx].valId = '';
        selectLen = parseInt(selectLen) - 1;
        isCancel = true;
      } else {
        group[idx].valId = gid;
        if (liid == '') selectLen = parseInt(selectLen) + 1;
      }
      //选中的值
      let arrSet = [];
      group.forEach(e => {
        if (e.valId != '') {
          arrSet.push(e.valId);
        }
      });
      //取消按钮  并且个数>2
      if (isCancel && parseInt(targetLen) - parseInt(selectLen) >= 2) {
        group.map(e => {
          if (e.valId == '') {
            for (var k = 0; k < e.val.length; k++) {
              e.val[k].isDisabled = '';
            }
          }
          return e;
        });
      } else if (parseInt(targetLen) - parseInt(selectLen) == 1) {
        //设置SKU项还差一个的时候的disabld状态

        group = group.map((e, index) => {
          if (e.valId == '') {
            const arrSetConst = arrSet;
            for (var k = 0; k < e.val.length; k++) {
              e.val[k].isDisabled = 'disabled';
              let arrr = [];
              arrr.push(e.val[k].valId);
              arrr = arrr.concat(arrSetConst);
              let sortArrPushOne = JSON.stringify(arrr.sort(function (a, b) {
                  return a - b;
                })),
                objSort = '';
              for (var i = 0; i < arrBuyStatusTwo.length; i++) {
                objSort = JSON.stringify(arrBuyStatusTwo[i].sort(function (a, b) {
                  return a - b;
                }));
                console.log(objSort, sortArrPushOne);
                if (objSort == sortArrPushOne) {
                  e.val[k].isDisabled = '';
                }
              }
            }
          } else {
            for (var k = 0; k < e.val.length; k++) {
              e.val[k].isDisabled = '';
            }
          }
          return e;
        });
      } else if (parseInt(targetLen) == parseInt(selectLen)) {
        const arrSetConst = arrSet;
        group = group.map((e, index) => {
          if (e.valId != gid) {
            for (var k = 0; k < e.val.length; k++) {
              if (!~arrSetConst.indexOf(e.val[k].valId)) {
                e.val[k].isDisabled = 'disabled';
                let nowArr = _.filter(arrSetConst, resTo => {
                  return e.valId != resTo;
                });
                nowArr.push(e.val[k].valId);
                let sortArrPushOne = JSON.stringify(nowArr.sort(function (a, b) {
                    return a - b;
                  })),
                  objSort = '';
                for (var i = 0; i < arrBuyStatusTwo.length; i++) {
                  objSort = JSON.stringify(arrBuyStatusTwo[i].sort(function (a, b) {
                    return a - b;
                  }));
                  if (objSort == sortArrPushOne) {
                    e.val[k].isDisabled = '';
                  }
                }
              } else {
                e.val[k].isDisabled = '';
              }
            }
          }
          return e;
        });
      }
      this.setData({
        selectLen,
        group: group
      });
      this.fetchPrice();
      this.fetchStock();
      this.fetchUnSelectText();
      this.fetchSelectText();
      this.fetchSkuId();
      this.fetchSelectSpecText();
    },
    fetchStock() {
      let {
          group,
          skus,
          skuLength
        } = this.data,
        stock = 0,
        group2 = group.filter(g => {
          return g.valId;
        }).map(g => {
          return g.valId;
        });
      // console.log(group2)
      if (group2.length === group.length) {
        stock = this.fetchSkuInfo(group2).stock || 0;
      } else {
        skus.forEach(sku => {
          stock += parseInt(sku.stock || 0, 10);
        });
      }
      this.setData({
        stock: stock,
        hasLength: group.length == group2.length ? true : false
      });
    },
    fetchPrice() {
      let {
        group,
        skus,
        unSelectText
      } = this.data;
      // console.log('skus===',skus)
      // console.log('group============',group)

      let a = group.filter(g => !g.valId);
      // console.log('a======',a)

      if (a == 0) {
        let stockNew = false;
        let isNewPrice = group.filter(g => {
          return g.valId;
        }).map(g => {
          return g.valId;
        });
        if (isNewPrice.length === isNewPrice.length) {
          stockNew = this.fetchSkuInfo(isNewPrice).goodsFlashSale || {};
        }
        this.setData({
          goodsFlashSaleData: stockNew.isGoodsFlashSale || false
        });
      }
      let price = '',
        group2 = group.filter(g => g.valId).map(g => g.valId);
      if (group2.length === group.length) {
        price = this.fetchSkuInfo(group2).price || 0;
      } else {
        price = Math.min.apply(null, skus.map(sku => Number(sku.price)));
        if (price === Infinity) {
          price = '';
        }
      }
      this.setData({
        price
      });
    },
    fetchUnSelectText() {
      let {
        group
      } = this.data;
      this.setData({
        unSelectText: group.filter(g => {
          return !g.valId;
        }).map(g => {
          return g.name;
        }).join(' ')
      });
    },
    fetchSelectText() {
      let {
        group
      } = this.data;
      this.setData({
        selectText: group.filter(g => {
          return g.valId;
        }).map(g => {
          return g.val.filter(val => {
            return val.valId === g.valId;
          })[0].name;
        }).join(' '),
        selectTextKey: group.filter(g => {
          return g.valId;
        }).map(g => {
          let name = g.val.filter(val => {
            return val.valId === g.valId;
          })[0].name;
          return g.name + '：' + name;
        })
      });
    },
    fetchSelectSpecText() {
      let skuImage = '';
      let flag = true;
      const specName = this.data.group.filter(g => g.valId).map(g => g.name + ':' + g.val.filter(val => {
        if (val.valId === g.valId) {
          if (flag) {
            skuImage = val.img || skuImage;
            if (val.isOrigin === '1' && val.img) {
              flag = false;
            }
          }
          return true;
        }
        return false;
      })[0].name).join(' ');
      this.setData({
        specName,
        skuImage
      });
    },
    addNum() {
      let {
        quantity,
        stock
      } = this.data;
      if (parseInt(quantity, 10) + 1 > stock) {
        return xhs.showToast({
          icon: 'none',
          title: '库存不足'
        });
      }
      this.setData({
        quantity: parseInt(quantity, 10) + 1
      });
    },
    /**
     * 绑定购买数量
     */
    bindNumInput({
      detail: {
        value: quantity
      }
    }) {
      quantity = parseInt(quantity, 10);
      let {
        stock
      } = this.data;
      if (quantity > stock) {
        xhs.showToast({
          icon: 'none',
          title: '库存不足'
        });
      }
      if (quantity) {
        this.setData({
          quantity: quantity < 1 ? 1 : quantity > stock ? stock : quantity
        });
      }
    },
    subtractNum() {
      let {
        quantity
      } = this.data;
      if (parseInt(quantity, 10) == 1) {
        return;
      }
      this.setData({
        quantity: parseInt(quantity, 10) - 1
      });
    },
    setOrderBy(e) {
      this.setData({
        orderBy: e.currentTarget.dataset.i
      }, () => {
        this.getOrganizationList();
      });
    },
    bindRegionChange(e) {
      this.setData({
        region: e.detail.value,
        serviceOrgId: '',
        serviceOrgInfo: {}
      });
      this.getNameCode(e.detail.code[0], e.detail.code[1], e.detail.code[2]);
    },
    /**
     * 设置地址编码
     */
    getNameCode(p, c, a) {
      let _that = this;
      getAreaList().then(res => {
        res.forEach(function (province) {
          if (province.areaCode == p) {
            _that.setData({
              provinceCode: province.id
            });
            if (c) {
              province.list.forEach(function (city) {
                if (city.areaCode === c) {
                  _that.setData({
                    cityCode: city.id
                  });
                  if (a) {
                    city.list.forEach(function (area) {
                      if (area.areaCode === a) {
                        _that.setData({
                          areaCode: area.id
                        });
                      }
                    });
                  }
                }
              });
            }
          }
        });
        this.getOrganizationList();
      });
    },
    getOrganizationList(address) {
      xhs.showLoading();
      let {
        goodsId,
        shareEmployeeId,
        provinceCode,
        cityCode,
        areaCode,
        orderBy,
        lng,
        lat
      } = this.data;
      if (address && address[3]) {
        lng = address[3].lng;
        lat = address[3].lat;
        this.setData({
          lng,
          lat
        });
      }
      app.$getData('/user/product-item/get-organization-list', {
        goodsId: goodsId,
        // shareEmployeeId:shareEmployeeId,
        provinceCode: provinceCode || '',
        cityCode: cityCode || '',
        areaCode: areaCode || '',
        orderBy,
        lng,
        lat
      }).then(data => {
        xhs.hideLoading();
        if (data.errCode == 0) {
          i++;
          this.setData({
            registratioList: data.data || [],
            isService: this.data.serviceOrgId == '' && data.data.length > 0 ? true : false
          });
          if (data.data.length == 1) {
            this.setData({
              serviceOrgId: data.data[0].orgId,
              serviceOrgInfo: data.data[0],
              isService: false
            });
          }
        } else {
          xhs.showToast({
            title: data.errInfo,
            icon: 'none',
            mask: true
          });
        }
      });
    },
    registrationTap(e) {
      let {
        value
      } = e.detail;
      let serviceOrgInfo = this.data.registratioList.find(item => item.orgId == value);
      this.setData({
        serviceOrgId: value,
        serviceOrgInfo: serviceOrgInfo
      });
    },
    fetchSkuId() {
      let {
          group
        } = this.data,
        skuId = '',
        group2 = group.filter(g => g.valId).map(g => g.valId);
      if (group2.length === group.length) {
        skuId = this.fetchSkuInfo(group2).id || 0;
      }
      this.setData({
        skuId
      });
    },
    fetchSkuInfo(vals) {
      return this.data.skus.filter(sku => !_.difference(sku.val, vals).length)[0] || {};
    },
    closeFn() {
      this.setData({
        isShow: false,
        goodsInfo: {},
        registratioList: [],
        group: [],
        price: '',
        //价格
        stock: '0',
        //库存
        selectText: '',
        unSelectText: '',
        quantity: '1',
        qShow: false,
        goodsBody: '',
        detailMedia: ''
      });
      this.triggerEvent('showfn');
    },
    toEmit() {
      let {
        quantity,
        stock,
        group,
        goodsInfoSku,
        skuId,
        goodsInfo,
        selectText,
        selectTextKey
      } = this.data;
      if (+quantity > stock) {
        return xhs.showToast({
          icon: 'none',
          title: '库存不足，无法加入购物车'
        });
      }
      let a = group.filter(g => !g.valId);
      if (a.length !== 0) {
        return xhs.showToast({
          icon: 'none',
          title: '请选择' + a[0].name
        });
      }
      let arr = group.map(e => {
        e.val = e.val.map(ee => {
          return ee.valId == e.valId;
        });
        return e;
      });
      let skuInfo = goodsInfoSku.filter(g => g.id == skuId);
      goodsInfo = _.extend(goodsInfo, {
        actualUnitPrice: skuInfo[0].price,
        price: skuInfo[0].price,
        code: skuInfo[0].code,
        isDel: 0,
        salenum: quantity,
        skuName: selectText,
        selectTextKey: selectTextKey,
        id: skuId
      });
      this.triggerEvent('skuData', goodsInfo);
      this.setData({
        selectTextKey: '',
        isShow: false,
        goodsInfo: {},
        registratioList: [],
        group: [],
        price: '',
        //价格
        stock: '0',
        //库存
        selectText: '',
        unSelectText: '',
        quantity: '1',
        qShow: false,
        goodsBody: '',
        detailMedia: ''
      });
    },
    // 购物车
    addTocart() {
      let {
        goodsId,
        skuId,
        quantity,
        stock,
        group,
        oldshareEmployeeId,
        roomId,
        qqLiveId,
        spreadActivityId,
        serviceOrgId,
        shareUserId,
        noteUserId,
        goodsInfo,
        notLocation,
        userCityId,
        cityName
      } = this.data;
      let {
        spreadLogId = '',
        spreadId = ''
      } = app.getPathOptions();
      if (goodsInfo.limitCityList.length > 0) {
        if (notLocation) {
          //没定位就重新定位
          this.getCityDate();
          return;
        } else if (userCityId == '') {
          return xhs.showToast({
            title: '仅限' + cityName + '用户购买',
            icon: 'none',
            mask: true
          });
        }
      }
      if (+quantity > stock) {
        return xhs.showToast({
          icon: 'none',
          title: '库存不足，无法加入购物车'
        });
      }
      let a = group.filter(g => !g.valId);
      if (a.length !== 0) {
        return xhs.showToast({
          icon: 'none',
          title: '请选择' + a[0].name
        });
      }
      if (this.data.type == '1' && this.data.serviceOrgId == '' && this.data.registratioList.length != '0') {
        // 是品项&&没选机构&&所在城市商家不等于0
        return xhs.showToast({
          icon: 'none',
          title: '请选择服务商家'
        });
      }
      app.$getData('/user/goods-cart/add', {
        goodsId,
        skuId,
        quantity,
        employeeUserId: oldshareEmployeeId,
        roomId,
        qqLiveId,
        spreadActivityId,
        spreadLogId,
        spreadId,
        serviceOrgId,
        shareUserId: noteUserId || shareUserId,
        userCityId
      }).then(data => {
        if (data.errCode == 0) {
          xhs.showToast({
            icon: 'none',
            title: '添加成功'
          });
          i = 0;
          this.triggerEvent('showfn');
        } else {
          xhs.showToast({
            icon: 'none',
            title: data.errInfo
          });
        }
      });
      this.setData({
        isShow: false,
        goodsInfo: {},
        registratioList: [],
        group: [],
        price: '',
        //价格
        stock: '0',
        //库存
        selectText: '',
        unSelectText: '',
        quantity: '1',
        qShow: false,
        goodsBody: '',
        detailMedia: ''
      });
    },
    preView(e) {
      const {
          url,
          link,
          type
        } = e.currentTarget.dataset,
        urls = this.data.goodsInfo.detailPic.map(p => {
          return p.url;
        });
      if (link) {
        xhs.navigateTo({
          url: homeNavigate(link, this.data.orgId)
        });
      } else {
        xhs.previewImage({
          current: url,
          // 当前显示图片的http链接
          urls: type == 'detail' ? urls : [url] // 需要预览的图片http链接列表
        });
      }
    },
    parseData(num) {
      var text = '';
      if (num > 9999) {
        text = (num / 10000).toFixed(1) + 'w';
      } else {
        text = num;
      }
      return text;
    }
  }
});